package com.appointmentmanager.web;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.appointmentmanager.model.Project;
import com.appointmentmanager.service.ProjectService;
import com.appointmentmanager.service.UserService;

@Controller
@RequestMapping("/newproject")
public class NewProjectController {

//	private Logger logger = LoggerFactory.getLogger(getClass()); 
	
	private UserService userService;
	private ProjectService projectService;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String displayNewProjectForm(Model model) {
		model.addAttribute("user", userService.getCurrentUser());
		
		return "newproject";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String processNewProjectSubmission(@RequestParam(value = "projectname", required = true) String name,
			@RequestParam(value = "description", required = false) String description,
			@RequestParam(value = "private", required = false) Boolean isPrivate,
			Model model) {
		
//		logger.debug(name + " " + description + " " + isPrivate);
		
		if (name.equals("")) {
			model.addAttribute("user", userService.getCurrentUser());
			return "newProjectError";
		}
		
		Project project = this.projectService.findProject(name);
		if (project != null) {
			model.addAttribute("user", userService.getCurrentUser());
			model.addAttribute("name", name);
			return "newProjectError";
		}
		
		Long uid = userService.getCurrentUser().getId();
		
		if (isPrivate != null) {
			projectService.addNewProject(name, description, isPrivate, uid);
		} else {
			projectService.addNewProject(name, description, false, uid);
		}

		return "redirect:/myproject";
	}
	
}